package com.zscat.mallplus.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

public class PayUtil {

    private static Logger logger = LoggerFactory.getLogger(PayUtil.class);

    /**
     * 商户ID//20001223,20001245
     */
    public static final String mchId = "10000001";
    /**
     * 加签key
     */
    public static final String reqKey = "klsghioergnjkfjk57879w3jhsdfkjhnji34784jihaUuiUijj";
    /**
     * 验签key
     */
    public static final String resKey = "dfseiopghsldngskl85956068989KHdgousi4yjklzndfgkljh";

    public static String baseUrl = "http://payment.wljiam.com";

    /**
     * 统一下单快捷支付
     *
     * @return
     */
//    public static String fastPayOrder() {
//        JSONObject paramMap = new JSONObject();
//        String mchOrderNo = String.valueOf(System.currentTimeMillis());
//        // 商户ID
//        paramMap.put("mchId", mchId);
//        // 商户订单号
//        paramMap.put("mchOrderNo", mchOrderNo);
//        // 支付渠道ID, WX_NATIVE(微信扫码),WX_JSAPI(微信公众号或微信小程序),WX_APP(微信APP),WX_MWEB(微信H5),ALIPAY_WAP(支付宝手机支付),ALIPAY_PC(支付宝网站支付),ALIPAY_MOBILE(支付宝移动支付)
//        paramMap.put("channelId", PayConstant.PAY_CHANNEL_HTL_PAY);
//        // 支付金额,cny单位分, htl单位个, eth单位GWEI
//        paramMap.put("amount", "50");
//        // 币种, cny-人民币
//        paramMap.put("currency", "coin");
//        // 用户地址,微信H5支付时要真实的
//        paramMap.put("clientIp", "211.94.116.218");
//        // 设备
//        paramMap.put("device", "WEB");
//        paramMap.put("subject", "支付测试");
//        paramMap.put("body", "支付测试");
//        // 回调URL
//        paramMap.put("notifyUrl", "http://192.168.1.40:8002/api/temple/common/payCointCallBack");
//        paramMap.put("param1", "{\"code\":\"O\",\"productName\":\"食品\",\"begin_time\":\"2018-07-03 18:16:05\",\"user_id\":\"2acacd2bd0c641fd974fddc5875f5910\"}");
//        //{"h5_info": {"type":"Wap","wap_url": "https://pay.qq.com","wap_name": "腾讯充值"}}
//        // 重定向地址
//        paramMap.put("redirectUrl", "http://m.bibi321.com");
//        String reqSign = PayDigestUtil.getSign(paramMap, reqKey);
//        // 签名
//        paramMap.put("sign", reqSign);
//        String url = baseUrl + "/pay/fastPay?";
//        Map<String, String> paramsMap = new HashMap();
//        paramsMap.put("params", paramMap.toJSONString());
//        String result = HttpClientsUtil.httpPostBody(url, 5000, paramsMap, "utf-8");
//        System.out.println("请求支付中心下单接口,响应数据:" + result);
//        Map retMap = JSON.parseObject(result);
//        //amount=50&body=支付测试&channelAccount=600200000000000000&channelId=HL_GUSD_ASYN_PAY&channelMchId=30080000&clientIp=211.94.116.218&createTime=Mon Jan 14 11:15:26 CST 2019&currency=gusd&device=WEB&isSuccess=true&mchId=10000000&mchOrderNo=1547435720645&notifyCount=0&notifyUrl=http://shop.bibi321.com/notify_test&payOrderId=1547435720645&paySuccTime=1547435721874&resCode=SUCCESS&retCode=SUCCESS&status=2&subject=支付测试&updateTime=Mon Jan 14 11:15:26 CST 2019&key=fywk6jsikh37672ks734kgklsl78qkgkjrt86wgsg64hsa74hrwj6hsabru764
//        //amount=50&body=支付测试&channelAccount=600200000000000000&channelId=HL_GUSD_ASYN_PAY&channelMchId=30080000&clientIp=211.94.116.218&createTime=1547435726000&currency=gusd&device=WEB&isSuccess=true&mchId=10000000&mchOrderNo=1547435720645&notifyCount=0&notifyUrl=http://shop.bibi321.com/notify_test&payOrderId=1547435720645&paySuccTime=1547435721874&resCode=SUCCESS&retCode=SUCCESS&status=2&subject=支付测试&updateTime=1547435726000&key=fywk6jsikh37672ks734kgklsl78qkgkjrt86wgsg64hsa74hrwj6hsabru764
//        if ("SUCCESS".equals(retMap.get("retCode")) && "SUCCESS".equalsIgnoreCase(retMap.get("resCode").toString())) {
//            // 验签
//            String checkSign = PayDigestUtil.getSign(retMap, resKey, "sign", "payParams");
//            String retSign = (String) retMap.get("sign");
//            if (checkSign.equals(retSign)) {
//                System.out.println("=========下单验签成功=========");
//                return mchOrderNo;
//            } else {
//                System.err.println("=========下单验签失败=========");
//                return null;
//            }
//        }
//        return mchOrderNo;
//    }

    // 统一下单,支付并充值
//    public static void payAndRechargeOrderTest() {
//        JSONObject paramMap = new JSONObject();
//        paramMap.put("mchId", mchId);                               // 商户ID
////        SnowflakeIdWorker idWorker0 = new SnowflakeIdWorker(21, 28);
////        paramMap.put("mchOrderNo", Long.toString(idWorker0.nextId()));     // 商户订单号
//        paramMap.put("mchOrderNo", Long.toString(System.currentTimeMillis()));     // 商户订单号
//        // 支付渠道ID, WX_NATIVE(微信扫码),WX_JSAPI(微信公众号或微信小程序),WX_APP(微信APP),WX_MWEB(微信H5),ALIPAY_WAP(支付宝手机支付),ALIPAY_PC(支付宝网站支付),ALIPAY_MOBILE(支付宝移动支付)
//        //UNION_PC、UNION_WAP
//        paramMap.put("channelId", PayConstant.PAY_CHANNEL_ALIPAY_WAP);
//        paramMap.put("amount", 100000);                                  // 支付金额,单位分
//        paramMap.put("currency", "cny");                            // 币种, cny-人民币
//        paramMap.put("clientIp", "211.94.116.218");                 // 用户地址,微信H5支付时要真实的
//        paramMap.put("device", "WEB");                              // 设备
//        paramMap.put("subject", "支付测试");
//        paramMap.put("body", "支付测试");
//        // 回调URL
//        paramMap.put("notifyUrl", "http://192.168.1.40:8002/api/temple/common/payNotify");
//        paramMap.put("param1", "{\"code\":\"CZ\",\"productName\":\"金币充值\",\"user_id\":\"2acacd2bd0c641fd974fddc5875f5910\", \"extraAmount\":\"1900\", \"currency\":\"coin\", \"extraChannelId\":\"" + PayConstant.PAY_CHANNEL_HTL_RECARGE + "\"}");
//        paramMap.put("param2", "");                                 // 扩展参数2，
//        //扩展信息现在已经不再需要填写，由后台服务来组织
////        paramMap.put("extra", "{\n" +
////                "  \"productId\": \"120989823\",\n" +
////                "  \"openId\": \"olnubwX4ymYu0vCZacRtLShuCQy8\",\n" +//注意：测试WX_JSAPI时需要预先通过其他途径获取到用户openID，这里填写的是我自己的
////                "  \"sceneInfo\": {\n" +
////                "    \"h5_info\": {\n" +
////                "      \"type\": \"Wap\",\n" +
////                "      \"wap_url\": \"http://localhost.com\",\n" +
////                "      \"wap_name\": \"支付测试\"\n" +
////                "    }\n" +
////                "  }\n" +
////                " ,\"discountable_amount\":\"0.00\"," + //面对面支付扫码参数：可打折金额 可打折金额+不可打折金额=总金额
////                "  \"undiscountable_amount\":\"0.00\"," + //面对面支付扫码参数：不可打折金额
////                "}");  // 附加参数
//
//        //{"h5_info": {"type":"Wap","wap_url": "https://pay.qq.com","wap_name": "腾讯充值"}}
//        paramMap.put("redirectUrl", "http://payshop.wljiam.com/notify_test");                         // 重定向地址
//        String reqSign = PayDigestUtil.getSign(paramMap, reqKey);
//        paramMap.put("sign", reqSign);                              // 签名
//        Map<String, String> paramsMap = new HashMap();
//        paramsMap.put("params", paramMap.toJSONString());
//        String reqData = getRequestParamString(paramsMap, "UTF-8");
//        System.out.println("请求支付中心下单接口,请求数据:" + reqData);
//        String url = baseUrl + "/pay/create_order?";
//        String result = XXPayUtil.call4Post(url + reqData);
//        System.out.println("请求支付中心下单接口,响应数据:" + result);
//    }

    /**
     * 将Map存储的对象，转换为key=value&key=value的字符
     *
     * @param requestParam
     * @param coder
     * @return
     */
    public static String getRequestParamString(Map<String, String> requestParam, String coder) {
        if (null == coder || "".equals(coder)) {
            coder = "UTF-8";
        }
        StringBuffer sf = new StringBuffer("");
        String reqstr = "";
        if (null != requestParam && 0 != requestParam.size()) {
            for (Map.Entry<String, String> en : requestParam.entrySet()) {
                try {
                    sf.append(en.getKey()
                            + "="
                            + (null == en.getValue() || "".equals(en.getValue()) ? "" : URLEncoder
                            .encode(en.getValue(), coder)) + "&");
                } catch (UnsupportedEncodingException e) {
                    logger.error(e.getMessage(), e);
                    return "";
                }
            }
            reqstr = sf.substring(0, sf.length() - 1);
        }
        logger.info("请求报文(已做过URLEncode编码):[" + reqstr + "]");
        return reqstr;
    }

    public static void main(String[] args) {
        //System.out.println(fastPayOrder());

//        Map<String, String> paramsMap = new HashMap<>();
//        paramsMap.put("userId", "2acacd2bd0c641fd974fddc5875f5910");
//        paramsMap.put("cardType", "coin");
//        System.out.println(JSON.toJSONString(paramsMap));
//        String result = HttpClientsUtil.httpPostBody(baseUrl + "/api/saCard/info", 5000, paramsMap, "utf-8");
//        JSONObject resultObj = JSON.parseObject(result);
//        if (resultObj.getInteger("code") == 0) {
//            JSONObject obj = resultObj.getJSONObject("obj");
//            System.out.println(obj.getInteger("remainPart"));
//        } else {
//            // 获取失败
//        }
//        HttpClientsUtil.httpPostBody(baseUrl + "/api/saCard/info", 5000, paramsMap, "utf-8");
//        payAndRechargeOrderTest();
    }

}
